import pymysql
from datetime import datetime

# ----------------------------- 配置（请根据环境调整） -----------------------------
DB_CONFIG = {
    'host': '127.0.0.1',
    'port': 3306,
    'user': 'root',
    'password': '159357wl',
    'db': 'yolo_app',
    'charset': 'utf8mb4'
}

# ----------------------------- 工具函数：数据库（示例，同步实现） -----------------------------

def ensure_user_table():
    """确保用户表存在（示例）。"""
    try:
        conn = pymysql.connect(**DB_CONFIG)
        cur = conn.cursor()
        cur.execute(
            """
            CREATE TABLE IF NOT EXISTS users (
                id INT AUTO_INCREMENT PRIMARY KEY,
                username VARCHAR(64) UNIQUE,
                phone VARCHAR(20) UNIQUE,
                account VARCHAR(64) UNIQUE,
                password VARCHAR(128),
                avatar_path TEXT,
                created_at DATETIME
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
            """
        )
        conn.commit()
        cur.close()
        conn.close()
    except Exception as e:
        print('数据库初始化失败：', e)


def add_user(username, phone, account, password, avatar_path=None):
    """尝试向数据库添加用户，若 phone 或 account 冲突则返回 False 和提示信息。"""
    try:
        conn = pymysql.connect(**DB_CONFIG)
        cur = conn.cursor()
        now = datetime.now()
        sql = "INSERT INTO users (username, phone, account, password, avatar_path, created_at) VALUES (%s,%s,%s,%s,%s,%s)"
        cur.execute(sql, (username, phone, account, password, avatar_path, now))
        conn.commit()
        cur.close()
        conn.close()
        return True, '注册成功'
    except pymysql.err.IntegrityError as ie:
        # 依据错误信息判断重复字段
        return False, '手机号或账号已注册'
    except Exception as e:
        return False, f'数据库错误: {e}'


def find_user_by_account(account):
    try:
        conn = pymysql.connect(**DB_CONFIG)
        cur = conn.cursor()
        cur.execute('SELECT id, username, phone, account, password, avatar_path FROM users WHERE account=%s', (account,))
        row = cur.fetchone()
        cur.close()
        conn.close()
        return row
    except Exception as e:
        print('查询用户失败：', e)
        return None